<template>
  <div>
    <!--搜索栏-->
    <el-form :inline="true" :model="condition" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="condition.userName" placeholder="请输入用户名" style="width: 150px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="condition.phonenumber" placeholder="请输入手机号码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="init(1)" style="margin-left: 50px">查询</el-button>
        <el-button type="danger" @click="handleAdd">添加</el-button>
        <el-button type="info" @click="clear">重置</el-button>
        <el-button type="success" @click="refresh" style="margin-left: 50px">刷新</el-button>
      </el-form-item>
    </el-form>
    <!--表单数据-->
    <el-table
        :data="userForm"
        style="width: 100%;">
      <el-table-column
          prop="loginName"
          label="账号名称"
          width="100"
      >
      </el-table-column>
      <el-table-column
          prop="userName"
          label="用户名"
          width="100"
      >
      </el-table-column>
      <el-table-column
          prop="avatar"
          label="头像"
          width="100"
      >
        <template v-slot="scope">
          <el-image
              style="width: 60px; height: 40px"
              :src="scope.row.avatar">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
          prop="userType"
          label="用户类型"
          :formatter="getUserType"
      >
      </el-table-column>
      <el-table-column
          prop="email"
          label="邮箱"
          width="200"
      >
      </el-table-column>
      <el-table-column
          prop="phonenumber"
          label="手机号"
          width="120"
      >
      </el-table-column>
      <el-table-column
          prop="sex"
          label="性别"
          :formatter="getSex"
      >
      </el-table-column>
      <el-table-column
          prop="status"
          label="帐号状态"
          :formatter="getStatus"
      >
      </el-table-column>
      <el-table-column
          prop="loginIp"
          label="最后登录ip"
          width="100"
      >
      </el-table-column>
      <el-table-column
          prop="loginDate"
          label="最后登陆时间"
          width="200"
      >
      </el-table-column>
      <el-table-column
          prop="createBy"
          label="创建者"
          width="100"
      >
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间"
          width="200"
      >
      </el-table-column>
      <el-table-column
          prop="remark"
          label="备注"
          width="100"
      >
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="250">
        <template v-slot="scope">
          <el-button type="primary" size="small" @click="queryRole(scope.row)">授予角色</el-button>
          <el-button type="success" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="deleteUser(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--授予角色表单-->
    <el-dialog title="角色列表" :visible.sync="dialogRoleVisible" width="30%">
      <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
      >全选
      </el-checkbox
      >
      <div style="margin: 15px 0"></div>
      <el-checkbox-group
          v-model="checkedRoles"
          @change="handleCheckedRolesChange"
      >
        <el-checkbox
            v-for="role in roleList"
            :label="role.roleId"
            :key="role.roleId"
        >{{ role.roleName }}
        </el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserAndRole">确 定</el-button>
      </span>
    </el-dialog>
    <!--添加或编辑表单-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules">
        <el-form-item
            label="账号名称"
            :label-width="formLabelWidth"
            prop="loginName"
        >
          <el-input
              v-model="form.loginName"
              autocomplete="off"
              placeholder="请输入账号名称"
          ></el-input>
        </el-form-item>
        <el-form-item
            label="用户名"
            :label-width="formLabelWidth"
            prop="userName"
        >
          <el-input
              v-model="form.userName"
              autocomplete="off"
              :disabled="flag===false"
              placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item
            label="密码"
            v-if="flag"
            :label-width="formLabelWidth"
            prop="password"
        >
          <el-input v-model="form.password" autocomplete="off" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="头像" :label-width="formLabelWidth">
          <el-upload
              class="avatar-uploader"
              action="/api/userManagement/user/upload"
              :headers="token"
              :show-file-list="false"
              name="file"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              ref="upload"
          >
            <img
                v-if="imageUrl"
                :src="imageUrl"
                class="avatar"
                style="width: 220px"
                alt=""
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户类型" :label-width="formLabelWidth">
          <el-radio v-model="form.userType" label="0">系统用户</el-radio>
          <el-radio v-model="form.userType" label="1">普通用户</el-radio>
        </el-form-item>
        <el-form-item label="用户邮箱" :label-width="formLabelWidth">
          <el-input v-model="form.email" autocomplete="off" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" :label-width="formLabelWidth">
          <el-input v-model="form.phonenumber" autocomplete="off" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="用户性别" :label-width="formLabelWidth">
          <el-radio-group v-model="form.sex">
            <el-radio label="0">男</el-radio>
            <el-radio label="1">女</el-radio>
            <el-radio label="2">保密</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账号状态" :label-width="formLabelWidth">
          <el-switch
              v-model="countStatus"
              active-color="#13ce66"
              inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="updateForm">确 定</el-button>
      </div>
    </el-dialog>
    <!--分页-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchForm.currentPage"
        :page-sizes="[1,2,5,10]"
        :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
  </div>

</template>
<script>
export default {
  name: "User",
  data() {
    return {
      condition: {},
      userForm: [],
      searchForm: {
        //分页
        currentPage: 1,
        pageSize: 5,
      },
      total: 0,
      //添加表单
      flag: true,
      //编辑表单
      dialogFormVisible: false,
      formLabelWidth: "120px",
      title: "用户编辑",
      form: {
        loginName: "",
        userName: "",
        password: "",
        userType: "",
        email: "",
        phonenumber: "",
        sex: "",
        status: "",
        avatar: "",
      },
      //表单验证
      rules: {
        loginName: [
          {required: true, message: "长度在 2 到 10 个字符", trigger: "blur"},
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        userName: [
          {required: true, message: "长度在 3 到 10 个字符", trigger: "blur"},
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {min: 6, max: 12, message: "由6-12字母和数字组成", trigger: "blur"},
          {
            required: true,
            pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$/,
            message: "必须由6-10字母和数字组成",
            trigger: "blur",
          },
        ],
      },
      imageUrl: "", //头像路径
      countStatus: true, //设置账号状态默认是开启
      token: {
        token: this.getToken()
      },
      //授予角色表单
      dialogRoleVisible: false,//授予角色弹框是否显示
      checkAll: false, //是否全选
      checkedRoles: [], //默认选中的角色
      roleList: [], //有效角色集合
      roleIds: "", //定义所有中的所选角色id集合
      isIndeterminate: true,
      roleUserId: "",
      roleUserName: "",
      staffInfo: {},//登陆者信息
    }
  },
  created() {
    this.init();
    this.initInfo();
    this.queryAllRole();
  },
  methods: {
    //获取所有的角色
    queryAllRole() {
      this.$http.get("/userManagement/role/selectAllRole").then((res => {
        if (res.data.code === 200) {
          this.roleList = res.data.data;
        } else {
          this.$message.error("查询失败");
        }
      }))
    },
    //获取用户角色
    queryRole(row) {
      this.roleUserId = row.userId;
      this.roleUserName = row.userName;
      //初始化选中
      this.checkedRoles = [];
      this.roleIds = "";
      this.$http.get("/userManagement/role/selectRole?id=" + row.userId).then((res => {
        if (res.data.code === 200) {
          this.dialogRoleVisible = true;
          console.log(res);
          for (let n of res.data.data) {
            this.checkedRoles.push(n.roleId);
            this.roleIds += n.roleId + ",";
          }
          //去掉最后一个逗号
          this.roleIds = this.roleIds.substring(0, this.roleIds.length - 1);
        } else {
          this.$message.error("查询失败");
        }
      }))
    },
    //删除用户
    deleteUser(row) {
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(row);
        this.$http.post("/userManagement/user/delete", row).then((res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: res.data.msg
            });
            //刷新
            this.refresh();
          } else {
            this.$message({
              type: 'error',
              message: res.data.msg
            });
          }
        }))
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //上传图片成功回调
    handleAvatarSuccess(res, file) {
      //回显上传图片
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.avatar = res.data;
    },
    getToken() {
      //   初始化token
      let token = sessionStorage.getItem("token");
      //2.判断token是否存在
      if (token) {
        return token;
      }
    },
    //上传前检查
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 8;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 8MB!');
      }
      return isJPG && isLt2M;
    },
    //初始化加载个人信息
    initInfo() {
      this.$http.get("/system/user/info").then((res => {
        if (res.data.code === 200) {
          this.staffInfo = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }));
    },
    //分页查询
    init(val) {
      if (val === 1) {
        this.searchForm.userName = this.condition.userName;
        this.searchForm.phonenumber = this.condition.phonenumber;
        this.searchForm.currentPage = 1;
      }
      this.$http.post("/userManagement/user/selectByPage", this.searchForm).then((res => {
        if (res.data.code === 200) {
          this.userForm = res.data.data.records;
          this.total = res.data.data.total;
        } else {
          this.$message.error("系统繁忙");
        }
      }))
    },
    //刷新
    refresh() {
      this.condition = {};
      this.searchForm.userName = "";
      this.searchForm.phonenumber = "";
      this.searchForm.currentPage = 1;
      this.searchForm.pageSize = 5;
      this.init();
    },
    //清空搜索条件
    clear() {
      this.condition.userName = "";
      this.condition.phonenumber = "";
    },
    //更改每页显示条数
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.init();
    },
    //更改当前页码数
    handleCurrentChange(val) {
      this.searchForm.currentPage = val;
      this.init();
    },
    //跳转编辑表单
    handleEdit(index, row) {
      this.flag = false;//密码框不显示
      this.dialogFormVisible = true; //让对话框显示
      this.title = "用户编辑"; //让title的值改变
      this.form = row; //给表单赋值
      this.imageUrl = row.avatar; //让头像回显
      this.countStatus = row.status === "0";
    },
    //跳转添加表单
    handleAdd() {
      this.form = {};
      this.flag = true;//密码框显示
      this.dialogFormVisible = true; //让对话框显示
      this.title = "用户添加"; //让title的值改变
    },
    //取消
    cancel() {
      this.dialogFormVisible = false;
      this.init();
      this.form = {};
    },
    //数据显示格式化
    getUserType(row) {
      if (row.userType === "0") {
        return "系统用户";
      } else {
        return "普通用户";
      }
    },
    getSex(row) {
      switch (row.sex) {
        case "0":
          return "男";
        case "1":
          return "女";
        default:
          return "保密";
      }
    },
    getStatus(row) {
      if (row.status === "0") {
        return "正常";
      } else {
        return "停用";
      }
    },
    //更新或添加表单
    updateForm() {
      if (this.title === "用户编辑") {
        if (this.countStatus) {
          this.form.status = "0"; //默认账号状态正常
        } else {
          this.form.status = "1"; //账号停用
        }
        this.$http.post("/userManagement/user/update?username="+this.staffInfo.userName,this.form).then((res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.msg);
            this.dialogFormVisible = false;
          } else {
            this.$message.error(res.data.msg);
            this.dialogFormVisible = false;
          }
        }))
      } else {
        if (this.form.userType === "" || this.form.userType === undefined) {
          this.$message.error("用户类型必须填写");
          return;
        }
        if (this.form.sex === "" || this.form.sex === undefined) {
          this.$message.error("性别必须填写");
          return;
        }
        if (this.countStatus) {
          this.form.status = "0"; //默认账号状态正常
        } else {
          this.form.status = "1"; //账号停用
        }
        this.$http.post("/userManagement/user/addUser?username="+this.staffInfo.userName,this.form).then((res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.msg);
            this.dialogFormVisible = false;
          } else {
            this.$message.error(res.data.msg);
            this.dialogFormVisible = false;
          }
        }))
      }
    },
    //角色全选
    handleCheckAllChange(val) {
      if (val) {
        if (this.roleIds !== null) {
          this.roleIds = "";
        }
        console.log(this.checkedRoles);
        for (let i = 0; i < this.roleList.length; i++) {
          const tempRI = this.roleList[i].roleId;
          this.checkedRoles.push(tempRI);
          this.roleIds += tempRI + ",";
        } //去掉最后一个逗号
        this.roleIds = this.roleIds.substring(0, this.roleIds.length - 1);
        this.roleIds = this.roleIds.split(",");
        console.log(this.roleIds);
      } else {
        this.checkedRoles = [];
        this.roleIds = "";
      }
    },
    //勾选角色
    handleCheckedRolesChange(value) {
      this.roleIds = value; //把勾选的角色id赋值给roleIds
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.roleList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.roleList.length;
    },
    //更新权限
    addUserAndRole() {
      if (this.roleIds === "") {
        this.roleIds = [];
      }
      console.log(this.roleIds);
      this.$http.post("/userManagement/role/updateRole?userId=" + this.roleUserId +"&roleIds="+this.roleIds).then((res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.msg);
          this.dialogRoleVisible = false;
        } else {
          this.$message.error(res.data.msg);
        }
      }))
    }
  },
}
</script>
<style scoped>

</style>
